package com.cdream.basic.algorithm.leetcode.map;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author cdream
 * @date 10/9/21
 */
public class Question352 {
    class SummaryRanges {
        TreeMap<Integer, Integer> intervals;

        public SummaryRanges() {
            intervals = new TreeMap<Integer,Integer>();
        }

        public void addNum(int val) {
            Map.Entry<Integer, Integer> ceilingEntry = intervals.ceilingEntry(val + 1);
            Map.Entry<Integer, Integer> floorEntry = intervals.floorEntry(val);

            if (floorEntry!=null && floorEntry.getKey()<=val&& floorEntry.getValue()>=val){
                return;
            }else{
                boolean isLeft = ceilingEntry!=null && ceilingEntry.getKey()-1 == val;
                boolean isRight = floorEntry!=null && floorEntry.getValue()+1 == val;
                if (isLeft && isRight){
                    intervals.remove(ceilingEntry.getKey());
                    intervals.put(floorEntry.getKey(),ceilingEntry.getValue());
                }else if (isRight){
                    intervals.put(floorEntry.getKey(),floorEntry.getValue()+1);
                }else if (isLeft){
                    intervals.remove(ceilingEntry.getKey());
                    intervals.put(ceilingEntry.getKey()-1,ceilingEntry.getValue());
                }else {
                    intervals.put(val,val);
                }
            }

        }

        public int[][] getIntervals() {
            int size = intervals.size();
            int[][] ans = new int[size][2];
            int index = 0;
            for (Map.Entry<Integer, Integer> entry : intervals.entrySet()) {
                int left = entry.getKey(), right = entry.getValue();
                ans[index][0] = left;
                ans[index][1] = right;
                ++index;
            }
            return ans;
        }
    }
}
